package org.example.c2;

/**
 * @author liu-rui
 * @date 2020/6/3 下午6:18
 * @description 通过Unsafe同步原语解决线程安全问题
 * @since
 */
public class Demo9 {
    public static void main(String[] args) throws InterruptedException {
        SumTask sumTask = new SumTask();
        sumTask.exec(new Counter());
    }


    static class Counter implements ICounter {
        private int sum;

        @Override
        public void add(int data) {
            MyUnSafe.getUnsafe().monitorEnter(this);

            try {
                sum += data;
            } finally {
                MyUnSafe.getUnsafe().monitorExit(this);
            }
        }

        @Override
        public int getSum() {
            MyUnSafe.getUnsafe().monitorEnter(this);

            try {
                return sum;
            } finally {
                MyUnSafe.getUnsafe().monitorExit(this);
            }
        }
    }
}
